package bookshop.service.impl;

import java.util.List;

import bookshop.dao.BookDao;
import bookshop.dao.CategoryDao;
import bookshop.dao.DaoFactory;
import bookshop.domain.Book;
import bookshop.domain.Category;
import bookshop.service.BookService;
import bookshop.service.helper.BookQueryHelper;
import bookshop.utils.Page;

public class BookServiceImpl implements BookService {

	public void newBook(Book book) {

		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");
		bookDao.saveBook(book);

		CategoryDao ctgDao = (CategoryDao) DaoFactory.getDao("categoryDao");
		Category ctg = ctgDao.getCategoryById(book.getCtg().getCtgId());
		ctg.setCtgBookAccount(ctg.getCtgBookAccount() + 1);
		ctgDao.update(ctg);
	}

	public List<Book> getAllBooks() {
		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");

		return bookDao.loadall();
	}

	public byte[] loadCover(String bookCode) {

		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");
		return bookDao.getBookCover(bookCode);

	}

	public Book getBookByCode(String bookCode) {
		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");

		return bookDao.getBookByCode(bookCode);
	}

	public void updateBook(Book book) {
		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");
		Book oldbook = bookDao.getBookByCode(book.getBookCode());
		Category oldctg = oldbook.getCtg();
		Category newctg = book.getCtg();

		if (!oldctg.getCtgId().equals(newctg.getCtgId())) {
			CategoryDao ctgDao = (CategoryDao) DaoFactory.getDao("categoryDao");
			oldctg.setCtgBookAccount(oldctg.getCtgBookAccount() - 1);
			ctgDao.update(oldctg);

			newctg = ctgDao.getCategoryById(newctg.getCtgId());
			newctg.setCtgBookAccount(newctg.getCtgBookAccount() + 1);
			ctgDao.update(newctg);

		}
		bookDao.update(book);
	}

	public void removeBook(String bookCode) {
		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");
		CategoryDao ctgDao = (CategoryDao) DaoFactory.getDao("categoryDao");
		Category ctg = bookDao.getBookByCode(bookCode).getCtg();
		ctg.setCtgBookAccount(ctg.getCtgBookAccount() - 1);
		ctgDao.update(ctg);

		bookDao.delBook(bookCode);
	}

	public List<Book> getBookById(int bookId) {
		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");
		return bookDao.getBooksByCtg(bookId);

	}

	public Page loadBooksByCondition(BookQueryHelper helper, Page page) {

		BookDao bookDao = (BookDao) DaoFactory.getDao("bookDao");
		page.setTotalRecNum(bookDao.countBooksByCondition(helper));
		page.setPageContent(bookDao.getScopedBooks(helper,
				page.getStartIndex(), page.getPageSize()));

		return page;
	}

}
